package com.manage.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.manage.dto.DepartmentDTO;
import com.manage.dto.add.DepartmentAddDTO;
import com.manage.dto.update.DepartmentUpdateDTO;
import com.manage.entity.Department;
import com.manage.result.PageResult;
import com.manage.server.mapper.DepartmentMapper;
import com.manage.server.service.DepartmentService;
import com.manage.vo.DepartmentVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author ddw
 * @description 针对表【department(部门表)】的数据库操作Service实现
 * @createDate 2025-04-13 13:37:08
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Override
    public boolean save(DepartmentAddDTO departmentAddDTO) {
        Department department = new Department();
        BeanUtils.copyProperties(departmentAddDTO, department);
        return this.save(department);
    }

    @Override
    public boolean updateById(DepartmentUpdateDTO departmentUpdateDTO) {
        Department department = new Department();
        BeanUtils.copyProperties(departmentUpdateDTO, department);
        return super.updateById(department);
    }

    @Override
    public PageResult<DepartmentVO> findDepartmentByPage(DepartmentDTO dto) {
        // 1. 处理分页参数（修正参数顺序问题）
        int pageNum = dto.getPageNum() != null && dto.getPageNum() > 0 ? dto.getPageNum() : 1;
        int pageSize = dto.getPageSize() != null && dto.getPageSize() > 0 ? dto.getPageSize() : 10;

        // 2. 创建分页对象（注意参数顺序：current, size）
        Page<Department> page = new Page<>(pageNum, pageSize);

        // 3. 构建动态查询条件
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();

        // 部门名称模糊查询
        if (StringUtils.hasText(dto.getName())) {
            queryWrapper.like("name", dto.getName().trim());
        }

        // 精确匹配条件
        if (dto.getId() != null) {
            queryWrapper.eq("id", dto.getId());
        }
        if (dto.getParentDepartmentId() != null) {
            queryWrapper.eq("parent_department_id", dto.getParentDepartmentId());
        }

        // 4. 执行分页查询
        Page<Department> resultPage = this.page(page, queryWrapper);

        // 5. 转换Entity到VO（处理特殊字段）
        Page<DepartmentVO> voPage = (Page<DepartmentVO>) resultPage.convert(entity -> {
            DepartmentVO vo = new DepartmentVO();
            BeanUtils.copyProperties(entity, vo);
            // 处理数据库字段和VO字段不一致的情况（如果有）
            // vo.setXXX(entity.getXXX());
            return vo;
        });

        // 6. 返回分页结果
        return PageResult.success(voPage);
    }
}